<?php

declare(strict_types=1);

namespace app\admin\controller;

use app\BaseController;
use app\common\model\Admin as AdminModel;
use app\common\validate\Admin as AdminValiDate;
use think\exception\ValidateException;
use think\facade\View;

class Admin extends BaseController
{
    protected $middleware = [
        \app\admin\middleware\LoginAuth::class
    ];

    // 管理员管理
    public function index()
    {
        $menu = [
            'name' => '管理员管理',
            'title' => '管理员列表'
        ];
        $searchfield = $this->request->param('search_field', 'username');
        $keyword = $this->request->param('keyword');
        $where = [];
        if ($searchfield && $keyword) {
            $where[] = [$searchfield, 'like', "%$keyword%"];
        }
        // 每页显示数量
        $num = 5;
        $AdminList = AdminModel::where($where)->paginate($num);
        // 当前页
        $page = $AdminList->currentPage();
        return view('', [
            'menu' => $menu,
            'AdminList' => $AdminList,
            'num' => $num,
            'page' => $page,
            'searchfield' => $searchfield,
            'keyword' => $keyword
        ]);
    }
    //启用/禁用
    public function state()
    {
        if ($this->request->isAjax()) {
            $ids = $this->request->param('ids');
            $action = $this->request->param('action');
            $LoginAdmin = $this->request->LoginAdmin;
            $adminid = isset($LoginAdmin['id']) ? $LoginAdmin['id'] : 0;
            // halt($LoginAdmin);
            $Admin = AdminModel::find($adminid);
            if (!$Admin) {
                return false;
            }
            $AdminList = AdminModel::whereIn('id', $ids)->column('id,state,username');
            if ($action == 1) {
                foreach ($AdminList as $item) {
                    if ($item['state'] == 1) {
                        $this->error("{$item['username']}已启用,请重新选择");
                    }

                    if (!in_array($item['id'], $ids)) {
                        $this->error("所选{$item['username']}不存在,请重新选择");
                    }
                    $result = AdminModel::whereIn('id', $ids)->update(['state' => 1]);

                    if ($result !== FALSE) {
                        $this->success('启用成功');
                    } else {
                        $this->error('启用失败');
                    }
                }
            } else {
                foreach ($AdminList as $item) {
                    if ($item['username'] == 'admin') {
                        $this->error('不能禁用超级管理员');
                    }

                    if ($item['state'] == 0) {
                        $this->error("{$item['username']}已禁用,请重新选择");
                    }

                    if (!in_array($item['id'], $ids)) {
                        $this->error("所选{$item['username']}不存在,请重新选择");
                    }
                }
                if (in_array($adminid, $ids)) {
                    $this->error('不能禁用当前登录用户');
                }

                $result = AdminModel::update(['state' => 0], ['id' => $ids]);

                if ($result !== FALSE) {
                    $this->success('禁用成功');
                } else {
                    $this->error("禁用失败");
                }
            }
        }
    }
    // 新增管理员
    public function add()
    {
        $menu = [
            'name' => '管理员管理',
            'title' => '新增管理员'
        ];
        if ($this->request->isPost()) {
            $params = $this->request->param();

            if ($params['password'] != $params['repass']) {
                $this->error('密码与确认密码不一致');
            }

            $salt = build_ranstr();

            $password = md5($params['password'] . $salt);

            $data = [
                'username' => $params['username'],
                'nickname' => $params['nickname'],
                'password' => $password,
                'salt' => $salt,
                'state' => $params['state']
            ];

            try {
                validate(AdminValiDate::class)->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }

            $Admin = new AdminModel();

            $result = $Admin->save($data);

            if ($result !== FALSE) {
                $this->success('新增管理员成功', (string)url('admin/admin/index'));
            } else {
                $this->error('新增管理员失败');
            }
        }
        return view('', [
            'menu' => $menu,
        ]);
    }
    //编辑管理员
    public function edit()
    {
        $menu = [
            'name' => '管理员管理',
            'title' => '编辑管理员'
        ];
        $LoginAdmin = $this->request->LoginAdmin;
        $adminid = $this->request->param('adminid');
        $Admin = AdminModel::find($adminid);
        if (!$Admin) {
            $this->error('账号不存在!');
        }
        // 判断是否有post提交
        if ($this->request->isPost()) {
            // 接收参数
            $params = $this->request->param();
            // 判断昵称是否为空
            if (empty($params['nickname'])) {
                $this->error('请输入昵称');
            }
            // 用于封装数据
            $data = [
                'nickname' => $params['nickname'],
                'state' => $params['state']
            ];
            if ($params['password'] || $params['repass']) {
                if (empty($params['password'])) {
                    $this->error('密码不能为空');
                }
                if (empty($params['repass'])) {
                    $this->error('确认密码不能为空');
                }
                if ($params['password'] != $params['repass']) {
                    $this->error('密码前后输入不一致，请重新输入');
                }
                if (md5($params['password'] . $Admin['salt']) == $Admin['password']) {
                    $this->error('新密码不能与原密码一致，请重新输入');
                }
                // 生成新的密码盐
                $salt = build_ranstr();
                // 密码盐与密码拼接组成加密的密码
                $password = md5($params['password'] . $salt);
                // 封装到data数组里
                $data['password'] = $password;
                $data['salt'] = $salt;
            }

            $result = $Admin->save($data);

            if ($result !== FALSE) {
                if ($LoginAdmin['id'] === $Admin['id'] && $params['password']) {
                    cookie('LoginAdmin', null);
                    $this->success('修改管理员成功，请重新登录', (string)url('/admin/index/login'));
                } else {
                    $this->success('修改管理员成功', (string)url('admin/admin/index'));
                }
            } else {
                $this->error('修改管理员失败');
            }
        }
        return view('', [
            'menu' => $menu,
            'Admin' => $Admin,
        ]);
    }
    // 删除管理员
    public function del()
    {
        if ($this->request->isAjax()) {
            $action = $this->request->param('action');
            $ids = $this->request->param('ids');
            $adminid = $this->request->param('adminid');
            $LoginAdmin = $this->request->LoginAdmin;
            // halt($LoginAdmin);
            $Admin = AdminModel::find($LoginAdmin['id']);
            if (!$Admin) {
                return false;
            }
            $AdminList = AdminModel::whereIn('id', $ids)->column('id,state,username');
            if ($action == 'del') {
                $Admin = AdminModel::find($adminid);
                if (!$Admin) {
                    $this->error('账号不存在');
                }
                $AdminModel = new AdminModel();
                $result = $AdminModel->where(['id' => $adminid])->delete();
                if ($result === false) {
                    $this->error('删除失败');
                } else {
                    $this->success('删除成功');
                }
            }else{
                foreach ($AdminList as $item) {
                    if ($item['username'] == 'admin') {
                        $this->error('不能删除超级管理员');
                    }

                    if (!in_array($item['id'], $ids)) {
                        $this->error("所选{$item['username']}不存在,请重新选择");
                    }
                }
                if (in_array($LoginAdmin['id'], $ids)) {
                    $this->error('不能删除当前登录用户');
                }

                $result = AdminModel::where(['id' => $ids])->delete();

                if ($result !== FALSE) {
                    $this->success('删除成功');
                } else {
                    $this->error("删除失败");
                }
            }
        }
    }
}
